package sessionBean;

import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import entityBean.Agenzia;
import entityBean.Cliente;
import entityBean.Operatore;

/**
 * Session Bean implementation class LoginCtrl
 */
@Stateless(name = "LoginCtrl")
@Remote(LoginCtrlRemote.class)
public class LoginCtrl implements LoginCtrlRemote {

	@PersistenceContext(unitName = "cvproject")
	private EntityManager manager;

	/**
	 * Default constructor.
	 */
	public LoginCtrl() {

		// TODO Auto-generated constructor stub

	}

	@Override
	public Operatore loginOperatore(String user, String password) {
		
		try {

			String s = "FROM operatore o WHERE o.codiceop =: user and o.password =: password";
			Query q = manager.createQuery(s);
			q.setParameter("user", user);
			q.setParameter("password", password);

			Operatore o = (Operatore) q.getSingleResult();

			return o;

		} catch (EntityNotFoundException e) {

			Operatore o = new Operatore();

			o.setCodOp("NonTrovato");

			return o;

		} catch (NonUniqueResultException e) {

			return null;

		}

	}

	@Override
	public Agenzia loginAgenzia(String user, String password) {

		try {

			String s = "FROM agenzia a WHERE a.username =: username and a.password =: password";
			Query q = manager.createQuery(s);
			q.setParameter("username", user);
			q.setParameter("password", password);

			Agenzia a = (Agenzia) q.getSingleResult();

			return a;

		} catch (EntityNotFoundException e) {

			Agenzia a = new Agenzia();

			a.setUsername("NonTrovato");

			return a;

		}

		catch (NonUniqueResultException e) {

			return null;

		}

	}

	@Override
	public Cliente loginCliente(String user, String password) {

		try {

			String s = "FROM cliente c WHERE c.username =: username and c.password =: password";
			Query q = manager.createQuery(s);
			q.setParameter("username", user);
			q.setParameter("password", password);

			Cliente c = (Cliente) q.getSingleResult();

			return c;

		} catch (EntityNotFoundException e) {

			Cliente c = new Cliente();

			c.setUsername("NonTrovato");

			return c;

		} catch (NonUniqueResultException e) {

			return null;

		}

	}

}
